#!/bin/sh
set -e

if [ "$HARDENING" = "" ]; then
  HARDENING="yes"
fi

if [ "$CXX" = "" ]; then
  CXX="g++"
fi

if [ "$STATIC" = "" ]; then
  STATIC="no"
fi

if [ "$REPRODUCIBLE" = "1" ]; then
  cat >> config.h << EOF
#define REPRODUCIBLE 1
EOF
fi

set -u

LD_RELRO=""
CF_PIE=""
LD_PIE=""
CF_FORTIFY=""
CF_STACK=""
BUILD_HOST="$(id -u -n)@$(hostname -f 2>/dev/null || hostname 2>/dev/null || echo localhost)"

cat >> config.h << EOF
#define BUILD_HOST "${BUILD_HOST}"
EOF

test_flags() {
  # test for relocation

  if [ `uname -s` = 'SunOS' ]; then
    return
  fi

  if $CXX -Wl,-help 2>/dev/null | grep 'z relro' >/dev/null; then
    LD_RELRO="-Wl,-z -Wl,relro"
    if $CXX -Wl,-help 2>/dev/null | grep 'z now' >/dev/null; then
      LD_RELRO="$LD_RELRO -Wl,-z -Wl,now"
    fi
    export LD_RELRO
  fi

  src=conftest.cc
  cat >$src <<EOF
#include <pthread.h>

__thread unsigned int t_id;
int
main ()
{
  t_id = 1;
  return 0;
}
EOF

  # test for PIE
  if $CXX $src -c -o a.out -fPIE -DPIE 2>/dev/null; then
    if [ "$STATIC" != "semi" ] && [ "$STATIC" != "full" ] && $CXX -pie -o a2.out a.out 2>/dev/null; then
      CF_PIE="-fPIE -DPIE"
      LD_PIE="-pie"
    fi
  fi

  # test for fortified source
  if $CXX $src -c -o a.out -O3 -D_FORTIFY_SOURCE=2; then
    CF_FORTIFY="-D_FORTIFY_SOURCE=2"
  fi

  # test for stack protector
  if $CXX $src -c -o a.out -O3 -fstack-protector; then
    CF_STACK="-fstack-protector"
    if $CXX $src -c -o a.out -O3 -fstack-protector --param ssp-buffer-size=4; then
      CF_STACK="$CF_STACK --param ssp-buffer-size=4"
    fi
  fi

  rm -f $src a.out a2.out
}

if [ "$HARDENING" != "no" ]; then
  test_flags
fi

sed -e "s/@LD_RELRO@/$LD_RELRO/g" -e "s/@LD_PIE@/$LD_PIE/g" -e "s/@CF_PIE@/$CF_PIE/g" -e "s/@CF_FORTIFY@/$CF_FORTIFY/g" -e "s/@CF_STACK@/$CF_STACK/g" < Makefile.in > Makefile

echo Testing dependencies and compiler.

MAKE=`which gmake || echo make`

echo Using $MAKE to build
$MAKE basic_checks
